package com.zyz.sunliky.service.serviceImpl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.zyz.sunliky.mapper.erp.ErpMapper;
import com.zyz.sunliky.mapper.yunshu.EhsMapper;
import com.zyz.sunliky.service.EhsService;
import com.zyz.sunliky.util.UUIDUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EhsServiceImpl implements EhsService{
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger(EhsServiceImpl.class);

    @Autowired
    ErpMapper erpMapper;
    @Autowired
    EhsMapper ehsMapper;

    @Value("${spring.yunshuurl}")
    private String URL;


    @Override
    public String getEhsChange(String id, String tokenId, String moduleId) {

        // 发送 HTTP GET 请求获取 replayToken
        String replayToken = getReplayToken(tokenId);
        if(replayToken.isEmpty())throw new RuntimeException("tokenid不能为空!");
        if(moduleId.isEmpty())throw new RuntimeException("moduleid不能为空!");
        String workflow = "workflow_dgzyxkz";
        /**查询表头**/
        List<Map<String,Object>> headList ;
        if(moduleId.equals("model_dhzyaqxkz")){
            workflow="workflow_dhzyaqxkz"; // workflow_dhzyaqxkz
            headList = ehsMapper.findHeadList(id);
        }else {
            headList = ehsMapper.findHeadListDG(id);
        }
        if(headList.isEmpty())throw new RuntimeException("没有此单据!");

        /**查询明细**/
        //List<Map<String,Object>> list_mx=ehsMapper.findBodyList(id);

        JSONObject object = new JSONObject();
        object.put("replayToken", replayToken);
        object.put("sheetCode", moduleId);
        // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowInstanceId", null);  // 添加workflowInstanceId字段，并将其值设为空字符串
        object.put("workflowCode", workflow);
        object.put("workItemId", null);
        String getuuid = UUIDUtils.getuuid();
        JSONObject data=new JSONObject();
        Map map = headList.get(0);
        data.put("id", getuuid);
        map.forEach((key,value)->{
            data.put(String.valueOf(key),value);
        });

        Map<String, List<Map<String, Object>>> contractData = fetchContractData(id);
        for (Map.Entry<String, List<Map<String, Object>>> entry : contractData.entrySet()) {
            JSONArray array=new JSONArray();
            String tableName = entry.getKey().substring(entry.getKey().indexOf('_') + 1); // 表名
            List<Map<String, Object>> rows = entry.getValue(); // 该表的数据列表
            for (Map<String, Object> listMx : rows) {
                JSONObject item = new JSONObject();
                listMx.forEach((key, value) -> {
                    item.put(String.valueOf(key), value);
                });
                item.remove("id");
                item.remove("sortKey");
                item.remove("parentId");
                item.remove("version");
                item.remove("modifier");
                array.add(item);
            }
            if (array.size() > 0){
                data.put(tableName, array);
            }
            if(moduleId.equals("model_dhzyaqxkz")){
                data.remove("ix67t_Sheet1670468632794");
                data.remove("ix67t_fbg");
            }else {
                data.remove("ix67t_fdhry");
                data.remove("ix67t_fdhzyaqcs");
                data.remove("ix67t_fmhsssfpb");
            }
        }
        //data.put("ix67t_model_dhzyaqxkz",array);
        JSONObject bizObject=new JSONObject();
        bizObject.put("schemaCode",moduleId);
        bizObject.put("sheetCode",moduleId);
        bizObject.put("workflowInstanceId",null);
        bizObject.put("data",data);
        object.put("bizObject",bizObject);
        //object.put("replayToken",replayToken);
        System.out.println(data);
        String s = object.toJSONString();
        String postResult = HttpRequest
                .post(URL+"/api/api/runtime/form/save")
                .header("Content-Type","application/json")
                .header("Authorization", "Bearer "+ tokenId)
                .body(s)
                .execute()
                .body();
        System.out.println(s);
        System.out.println(postResult);

        return postResult;
    }

    public Map<String, List<Map<String, Object>>> fetchContractData(String id) {
        String[] tableNames = {
                "ix67t_fdhry",
                "ix67t_fdhzyaqcs",
                "ix67t_fmhsssfpb",
                "ix67t_Sheet1670468632794",
                "ix67t_fbg"
        };

        Map<String, List<Map<String, Object>>> allData = new HashMap<>();
        for (String tableName : tableNames) {
            List <Map<String, Object>> results = ehsMapper.getContractByfhtbh(id, tableName);
            allData.put(tableName, results); // 将每张表的数据保存到结果中
        }
        return allData;
    }

    public String getReplayToken(String tokenid) {
        String replayToken = "";
        try {
            // 发送 HTTP GET 请求并获取响应
            String response = HttpRequest.get("http://122.225.90.194:9555/api/api/runtime/form/getReplayToken")
                    .header("Accept", "application/json")
                    .header("Authorization", "Bearer " + tokenid)
                    .timeout(5000)
                    .execute()
                    .body();
            // 打印整个响应字符串
            System.out.println("Response: " + response);
            // 解析 JSON 响应
            JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();

            // 获取名为"data"的字段的值
            replayToken = jsonObject.get("data").getAsString();
            // 打印 data 字段的值
            System.out.println("replayToken: " + replayToken);
        } catch (Exception e) {
            // 捕获可能的异常
            e.printStackTrace();
        }
        return replayToken;
    }
}
